import { Component } from '@angular/core';
import {App, IonicPage, NavController, NavParams} from 'ionic-angular';
import {HttpService} from "../../providers/HttpService";
import {InfoProvider} from "../../providers/InfoProvider";
import {CommProvider} from "../../providers/CommProvider";

/**
 * Generated class for the LoginPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

    login: {phone: string, password: string} = {
        phone: null,
        password: null,
    };
    first_page: boolean;

    constructor(public navCtrl: NavController, public navParams: NavParams,
                private app: App,
                private commProvider: CommProvider,
                private infoProvider: InfoProvider,
                private httpService: HttpService) {
        this.first_page = !navParams.get('guest_login');
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad LoginPage');
    }

    onLoginSubmit() {
        console.log('onLoginSubmit: ', this.login);
        this.httpService.instance()
            .setUrl('/user/userLogin')
            .setBody(this.login)
            .postRequest()
            .then(res => {
                if (res.status == 0) {
                    HttpService.setAuthPrimary(res.data.token);
                    this.infoProvider.setUserInfo(res.data);
                    this.commProvider.showToast('登录成功');
                    this.app.getRootNav().setRoot('TabsPage');
                }
            });
    }

    onGuestLogin() {
        this.infoProvider.setUserInfo({
            type: -1,
            phone: '游客账号',
            name: '游客'
        });
        this.app.getRootNav().setRoot('TabsPage');
    }

    onBack() {
        this.navCtrl.pop();
    }

    onPasswordSubmit() {
        this.navCtrl.push('PasswordPage');
    }

    onRegisterSubmit() {
        this.navCtrl.push('RegisterPage');
    }

    onEnvSwitch() {
        let envArray: Array<any> = [
            {
                title: '开发环境',
                value: 0,
                checked: HttpService.envType == 0
            },
            {
                title: '生产环境',
                value: 1,
                checked: HttpService.envType == 1
            }
        ];
        this.commProvider.showRadioAlert('环境切换', envArray).then(data => {
            console.log(data);
            HttpService.setHttpApi(Number(data));
        });
    }
}
